﻿// ----------------------------------------------------------------------
// <author name="Moses Kehengu"/>
// <copyright file="Translations.cs" company="Futures Group International">
//     Copyright statement. All right reserved
// </copyright>
//
// ------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GenericTools;
using System.Text.RegularExpressions;
using DataModels.Common;
using DataModels.Enumerations;

namespace ReportingManagement
{
    public partial class MainWindow
    {
        private int englishTranslationID;
        private int kiswahiliTranslationID;
        private string originalText;
        private List<string> placeHolders;
        private List<string> missingPlaceHolders;
        private bool reloadTranslation = true;

        private bool tabPageTranslationsLoaded = false;

        private void PopulateTranslationList()
        {
            int languageID = rdoEnglish.Checked ? 1 : 2;
            int selectedIndex = lstTranslations.SelectedIndex;
            lstTranslations.Items.Clear();
            lstTranslations.SuspendLayout();

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetAllTranslationByLanguage(languageID);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            foreach (DataRow row in dataTable.Rows)
            {
                ListItem i = new ListItem();
                i.Text = row["LText"].ToString();
                i.Value = row["LabelNo"];
                lstTranslations.Items.Add(i);
            }
            lstTranslations.ResumeLayout();

            try
            {
                lstTranslations.SelectedIndex = selectedIndex;
            }
            catch { }
        }

        private void FillTranslationDetails()
        {
            ListItem i = (ListItem)lstTranslations.SelectedItem;
            originalText = i.Text;
            txtLabelID.Text = i.Value.ToString();

            int englishLanguage = 1;
            int kiswahiliLanguage = 2;
            int labelNo = int.Parse(i.Value.ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            DataTable dataTable = Utilities.GetTranslationByLabelNo(englishLanguage, labelNo);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            txtEnglish.Text = dataTable.Rows[0]["LText"].ToString();
            englishTranslationID = int.Parse(dataTable.Rows[0]["TransID"].ToString());

            Cursor.Current = Cursors.WaitCursor;
            toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
            dataTable = Utilities.GetTranslationByLabelNo(kiswahiliLanguage, labelNo);
            Cursor.Current = Cursors.Default;
            toolStripStatusLabel.Text = "Ready";

            txtKiswahili.Text = dataTable.Rows[0]["LText"].ToString();
            kiswahiliTranslationID = int.Parse(dataTable.Rows[0]["TransID"].ToString());

            placeHolders.Clear();
            string pattern = @"<NUMBER.>|<USERNAME>|<SENDERNUM>|<FACILITYNAME>|{\d}";
            MatchCollection matches = Regex.Matches(originalText, pattern);
            foreach (Match m in matches)
            {
                foreach (Group g in m.Groups)
                {
                    string placeHolder = g.Value;
                    if (!String.IsNullOrEmpty(placeHolder))
                    {
                        if (!placeHolders.Contains(placeHolder))
                        {
                            placeHolders.Add(placeHolder);
                        }
                    }
                }
            }
        }

        private void lstTranslations_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FillTranslationDetails();
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private void rdoEnglish_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoEnglish.Checked)
            {
                try
                {
                    PopulateTranslationList();
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void rdoKiswahili_CheckedChanged(object sender, EventArgs e)
        {
            if (rdoKiswahili.Checked)
            {
                try
                {
                    PopulateTranslationList();
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            FillTranslationDetails();
        }

        private void btnSaveTranslation_Click(object sender, EventArgs e)
        {
            if ((AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DATA_ACCESS) ||
                (AppConfiguration.AccessMethod == DataAccessMethod.OFFLINE_DIRECT_ACCESS))
            {
                string message = @"The application is running in offline mode. " +
                    "You can not perform any activities that require server " +
                    "connection while you are offline. " +
                    "\n\nYou are current operation will not be processed!";
                MessageBox.Show(this, message, AppConfiguration.ApplicationName,
                    MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            bool okToContinue = ValidatePlaceHolders(txtEnglish.Text);
            if (!okToContinue)
            {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.Append("\n\nRequired Placeholders are:");
                foreach (string p in placeHolders)
                {
                    sBuilder.Append("\n\t" + p);
                    if (missingPlaceHolders.Contains(p)) sBuilder.Append(" - Missing");
                }

                MessageBox.Show(this,
                    String.Format("One or more placeholder is missing for label {0} in English translations {1}",
                    txtLabelID.Text, sBuilder.ToString()),
                    "Translation Manager", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            okToContinue = ValidatePlaceHolders(txtKiswahili.Text);
            if (!okToContinue)
            {
                StringBuilder sBuilder = new StringBuilder();
                sBuilder.Append("\n\nRequired Placeholders are:");
                foreach (string p in placeHolders)
                {
                    sBuilder.Append("\n\t" + p);
                    if (missingPlaceHolders.Contains(p)) sBuilder.Append(" - Missing");
                }

                MessageBox.Show(this, String.Format("One or more placeholder is missing for label {0} in Kiswahili translations {1}",
                    txtLabelID.Text, sBuilder.ToString()),
                    "Translation Manager", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                btnSaveTranslation.Enabled = false;
                toolStripStatusLabel.Text = "Loading data, please wait..."; Application.DoEvents();
                Utilities.UpdateTranslation(kiswahiliTranslationID, txtKiswahili.Text);
                Utilities.UpdateTranslation(englishTranslationID, txtEnglish.Text);
                btnSaveTranslation.Enabled = true;
                Cursor.Current = Cursors.Default;
                toolStripStatusLabel.Text = "Ready";

                // TODO: Update Translation list effectively after update
                MessageBox.Show(this, String.Format("You have successfully updated label {0} translations", txtLabelID.Text),
                    "Translation Manager", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                DisplayErrorMessage(ex);
            }
        }

        private bool ValidatePlaceHolders(string translation)
        {
            bool havePlaceHolders = true;
            missingPlaceHolders.Clear();
            foreach (string placeHolder in placeHolders)
            {
                if (translation.Contains(placeHolder)) continue;
                else
                {
                    havePlaceHolders = false;
                    missingPlaceHolders.Add(placeHolder);
                }
            }
            return havePlaceHolders;
        }

        private void tabPageTranslations_Enter(object sender, EventArgs e)
        {
            if (!tabPageTranslationsLoaded)
            {
                try
                {
                    placeHolders = new List<string>();
                    missingPlaceHolders = new List<string>();
                    PopulateTranslationList();

                    try
                    {
                        lstTranslations.SelectedIndex = 0;
                    }
                    catch { }

                    tabPageTranslationsLoaded = true;
                }
                catch (Exception ex)
                {
                    DisplayErrorMessage(ex);
                }
            }
        }
    }
}
